package com.yllt4cloud.push.server;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.ChannelGroupFuture;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2015/11/18.
 */
@Component
public class NettyServer {
	
	private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
	
    public static final ChannelGroup allChannels = new DefaultChannelGroup();
    
    @Autowired
    private ServerPipelineFactory httpServerPipelineFactory;

    private Channel channel = null;

    private ChannelFactory factory = null;

    private ServerBootstrap bootstrap = null;

    @Value("${netty.server.port}")
    public Integer port;

    public void start() {

        factory = new NioServerSocketChannelFactory(
                Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());
        this.bootstrap = new ServerBootstrap(factory);
        //通过xml装载PipelineFactory
//        ServerPipelineFactory httpServerPipelineFactory = (ServerPipelineFactory) applicationContext.getBean("serverPipelineFactory");
        this.bootstrap.setPipelineFactory(httpServerPipelineFactory);
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);

        channel = bootstrap.bind(new InetSocketAddress(port));
        allChannels.add(channel);

        logger.info("server start");
    }

    @PreDestroy
    public void stop() {
        ChannelGroupFuture future = allChannels.close();
        future.awaitUninterruptibly();
        if (factory != null) {
            factory.releaseExternalResources();
        }
        logger.info("server stop.");
    }



    @PostConstruct()
    public void init(){
        //需要开启一个新的线程来执行netty server 服务器
        new Thread(new Runnable() {
            public void run() {
                start();
            }
        }).start();
    }
}
